const jwt = require('jsonwebtoken')
const secretOrPublicKey = 'json-web-token-siwi' //TODO 通用配置
class Jwt {
    constructor() {

    }
    /**
     * 加密token
     * data :{id:'59a62b0b790c1a5ea72b1ea3', username: 'Mankong'}
     * @param {any} data 
     * @returns 
     * @memberof Jwt
     */
    async sign(data) {
        let token  = await jwt.sign({ user: data }, secretOrPublicKey, { expiresIn: '24h' })
        return token
    }
    /**
     * 验证token
     * 
     * @param {any} token 
     * @returns 
     * @memberof Jwt
     */
    async verify(token) {
        try {
            let data = await jwt.verify(token, secretOrPublicKey)
            return data
        } catch (error) {
            return false
        }
    }

    /**
     * 解密token
     * 
     * @param {any} token 
     * @returns 
     * @memberof Jwt
     */
    async decode(token) {
        try {
            let data = jwt.decode(token, {complete: true})
            return data
        } catch (error) {
            return false
        }
    }

}

module.exports = new Jwt()